import { _decorator, Component, Node, BoxCollider2D, CircleCollider2D, Contact2DType, IPhysics2DContact, Size, Sprite, UITransform, Vec3 } from 'cc';
import { GlobalConfig } from '../../Init/Config/GlobalConfig';
import { GlobalEnum } from '../../Init/Config/GlobalEnum';
const { ccclass, property } = _decorator;
/**敌方碰撞体 */
@ccclass('EnemyBarrier')
export class EnemyBarrier extends Component {
    //叠加的速度
    addSpd = GlobalConfig.Barrier.addSpd;
    maxX = 0;
    minX = 0;
    collider: BoxCollider2D = null;

    setData(d: { parent: Node, p: Vec3, r: Vec3, }) {
        this.node.parent = d.parent;
        this.node.setPosition(d.p);
        // this.node.eulerAngles = d.r;
        // //
        let trans = this.node.getComponent(UITransform);
        // 注册单个碰撞体的回调函数
        this.collider = this.getComponent(BoxCollider2D);
        if (this.collider) {
            this.collider.size = trans.contentSize;
            this.collider.apply();
            let cw = this.collider.size.width * 0.5;
            this.maxX = cw + this.node.worldPosition.x;
            this.minX = -cw + this.node.worldPosition.x;

            this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            this.collider.on(Contact2DType.END_CONTACT, this.onEndContact, this);
        }

        let sp = this.node.getComponent(Sprite);
        if (sp) {
            sp.enabled = GlobalConfig.isShow2dCollider;
        }
    }

    onDisable() {
        if (this.collider) {
            this.collider.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            this.collider.off(Contact2DType.END_CONTACT, this.onEndContact, this);
        }
    }
    /**检测分组 //touchPlayerId 僵尸 平民*/
    checkGroupArr = [1 << 1, 1 << 5, 1 << 6];
    // 只在两个碰撞体开始接触时被调用一次
    onBeginContact(selfCollider: BoxCollider2D, otherCollider: CircleCollider2D, contact: IPhysics2DContact | null) {
        // 被碰撞的物体-速度修正

        if (otherCollider.body[GlobalEnum.ExtralProp.addLineVec] && this.checkGroupArr.indexOf(otherCollider.group) >= 0) {
            //上下方向
            if (otherCollider.node.worldPosition.x <= this.maxX &&
                otherCollider.node.worldPosition.x >= this.minX) {
                otherCollider.body[GlobalEnum.ExtralProp.addLineVec].x = otherCollider.body.linearVelocity.x > 0 ? this.addSpd.x : -this.addSpd.x;
            } else {
                otherCollider.body[GlobalEnum.ExtralProp.addLineVec].x = 0;
                otherCollider.body[GlobalEnum.ExtralProp.addLineVec].y = otherCollider.body.linearVelocity.y > 0 ? this.addSpd.y : -this.addSpd.y;
            }
        }
    }

    onEndContact(selfCollider: BoxCollider2D, otherCollider: CircleCollider2D, contact: IPhysics2DContact | null) {
        // 被碰撞的物体-速度修正
        if (otherCollider.body[GlobalEnum.ExtralProp.addLineVec] && this.checkGroupArr.indexOf(otherCollider.group) >= 0) {
            otherCollider.body[GlobalEnum.ExtralProp.addLineVec].set(0, 0);
        }
    }

}

